// axios 封装
import axios, { InternalAxiosRequestConfig, AxiosResponse, AxiosRequestConfig } from 'axios'
import { Message } from '@arco-design/web-react'
Message.config({
  maxCount: 1
})

const axiosInstance = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 60 * 60 * 1000,
  headers: {
    'Content-Type': 'application/json'
  }
})

axiosInstance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = localStorage.getItem('token')
    config.headers.Authorization = 'Bearer ' + token
    // 请求拦截
    return config
  },
  (error: any) => {
    // 请求错误
    return Promise.reject(error)
  }
)
axiosInstance.interceptors.response.use(
  (response: AxiosResponse) => {
    const data = response.data
    // 请求异常
    const status = response.status?.toString()
    if (status.startsWith('2')) {
      // 如果data中的status 不为success 统一提示错误
      if (data.status === 'error' && data.code !== 200) {
        // 业务错误
        Message.error(data.msg)
        return Promise.reject(data)
      }
      return Promise.resolve(data.data)
    }

    Message.error('系统异常')
    return Promise.reject(response)
  },
  (error: any) => {
    const { response } = error
    const status = response?.status?.toString()
    switch (status) {
      case '401':
        Message.error('请先登录')
        window.location.href = '/login'
        break
    }
    // 响应错误
    Message.error(response?.data?.message || error.message)
    return Promise.reject(error)
  }
)

export const get = (url: string, params?: any) => {
  return axiosInstance.get(url, {
    params
  })
}

// Post请求

export const post = (url: string, data?: any, config?: AxiosRequestConfig) => {
  return axiosInstance.post(url, data, config)
}

// put 请求
export const put = (url: string, data?: any) => {
  return axiosInstance.put(url, data)
}
// putch 请求
export const putch = (url: string, data?: any) => {
  return axiosInstance.patch(url, data)
}

// del 请求
export const del = (url: string, data?: any) => {
  return axiosInstance.delete(url, data)
}

export default axiosInstance
